package cn.hackcloud.concurrency.per.chat;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 聊天服务端
 * by hackcloud.cn
 */
public class ChatServer {

    //服务端接口
    private final int port;
    //定义线程池
    private ThreadPoolExecutor threadPool;
    //服务端Socket
    private ServerSocket serverSocket;


    public ChatServer(int port) {
        this.port = port;
    }

    //默认端口
    public ChatServer() {
        this(13312);
    }

    public void startServer() throws Exception {
        //创建线程池，核心线程数量为2，最大线程数为4，队列中最大可加入500个任务
        this.threadPool = new ThreadPoolExecutor(2, 4,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(500));
        this.serverSocket = new ServerSocket(port);
        this.serverSocket.setReuseAddress(true);
        this.listen();
    }

    private void listen() throws IOException {
        for (; ; ) {
            final Socket client = serverSocket.accept();
            this.threadPool.execute(new ClientHandler(client));
        }
    }
}
